﻿using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Net;
using System.Web;
using System.Text;
using System.Web.Security;
using System.IO;
namespace EmoneyWeiXinCommon
{
    public class Common
    {
        //public static readonly  int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["listPageSize"]);
        //#region valid
        //public const string Error_Image_Src = "../images/Error.gif";
        //public static void ShowValid(List<RuleViolation> rvList,Control container)
        //{
        //    ValidInfo vi = null;
        //    Control control = null;
        //    for (int i = 0; i < rvList.Count; i++)
        //    {
        //        control = container.FindControl(rvList[i].ValidInfoName);
        //        if (control != null)
        //        {
        //            vi = (ValidInfo)control;
        //            vi.ImageSrc = Error_Image_Src;
        //            vi.Message = rvList[i].ValidMessage;
        //            vi.Visible = true;
        //        }
        //    }
        //}
        //public static void ShowValid(ValidInfo vi,string validMessage)
        //{
        //    vi.ImageSrc = Error_Image_Src;
        //    vi.Message = validMessage;
        //    vi.Visible = true;
        //}
        //public static void ShowValid(Control control, string validMessage)
        //{

        //    ValidInfo vi = (ValidInfo)control;
        //    vi.ImageSrc = Error_Image_Src;
        //    vi.Message = validMessage;
        //    vi.Visible = true;
        //}
        //public static void ClearValid(Control container)
        //{
        //    Control control = null;
        //    ValidInfo vi = null;          
        //    for (int i = 0; i < container.Controls.Count; i++)
        //    {
        //        control = container.Controls[i];
        //        if(control is ValidInfo)
        //        {
        //            vi = (ValidInfo)control;
        //            vi.ImageSrc = "";
        //            vi.Message = "";
        //            vi.Visible = false;
        //        }
        //    }
        //}
        //public static void ClearValid(ValidInfo control)
        //{
        //    control.ImageSrc = "";
        //    control.Message = "";
        //    control.Visible = false;
        //}
        //#region regular
        ////http://blog.csdn.net/jojo_blog/archive/2005/12/05/544214.aspx 
        ////http://blog.csdn.net/zhihua_1983/archive/2007/01/01/1472068.aspx
        //public static bool CheckDecimal(string str)
        //{
        //    return Regex.IsMatch(str, @"^(-?\d+)(\.\d+)?$");
        //}
        //public static bool CheckDecimalID(string str)
        //{
        //    return Regex.IsMatch(str,@"^\d+$");
        //}
        //public static bool CheckInt(string str)
        //{
        //    return Regex.IsMatch(str, @"^-?\d+$");
        //}
        //#endregion

        //#endregion  


        public static string GetClientIp()
        {
            String clientIP = "";
            if (System.Web.HttpContext.Current != null)
            {
                clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(clientIP) || (clientIP.ToLower() == "unknown"))
                {
                    clientIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];
                    if (string.IsNullOrEmpty(clientIP))
                    {
                        clientIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                }
                else
                {
                    clientIP = clientIP.Split(',')[0];
                }
            }
            return clientIP;
        }


        public static void Alert(Page page, string msg)
        {
            page.ClientScript.RegisterStartupScript(typeof(string), "js", "alert(\"" + msg + "\");", true);
        }
        public static string GetRealValue(object obj)
        {
            string value = "";
            try
            {
                value = obj.ToString();
            }
            catch
            { }
            return value;
        }

        public static int[] generateSortData(int c)
        {
            int[] sortData = new int[c];
            while (c > 0)
            {
                sortData[c - 1] = c;
                c--;
            }
            return sortData;
        }
        /// <summary>
        /// Get the values in the [container],and then create a instance of [type],and return it.
        /// </summary>
        /// <returns></returns>
        private static object ContentIntoObject(Control container, Object obj)
        {
            PropertyInfo[] pis = obj.GetType().GetProperties();
            Control control;
            object objValue;
            foreach (PropertyInfo pi in pis)
            {
                objValue = null;
                control = container.FindControl(pi.Name);
                if (control != null)
                {
                    if (control is TextBox)
                    {
                        objValue = ((TextBox)control).Text;
                    }
                    else if (control is CheckBox)
                    {
                        objValue = ((CheckBox)control).Checked;
                    }
                    else if (control is DropDownList)
                    {
                        objValue = ((DropDownList)control).SelectedValue;
                    }
                    else if (control is Label)
                    {
                        objValue = ((Label)control).Text;
                    }
                    if (objValue != null && !objValue.ToString().Equals(String.Empty))
                        if (!objValue.Equals(null))
                            pi.SetValue(obj, getValueByType(objValue, pi.PropertyType), null);
                }
            }
            return obj;
        }
        /// <summary>
        /// Get the values in the [container],and then create a instance of [type],and return it.
        /// </summary>
        /// <returns></returns>
        public static object ContentIntoObject(Control container, Object obj, string[] prefixs)
        {
            PropertyInfo[] pis = obj.GetType().GetProperties();
            Control control;
            object objValue;
            foreach (PropertyInfo pi in pis)
            {
                objValue = null;
                control = null;
                if (prefixs != null)
                    for (int i = 0; i < prefixs.Length; i++)
                    {
                        control = container.FindControl(prefixs[i] + pi.Name);
                        if (control != null) break;
                    }
                else
                    control = container.FindControl(pi.Name);
                if (control != null)
                {
                    if (control is TextBox)
                    {
                        objValue = ((TextBox)control).Text;
                    }
                    else if (control is CheckBox)
                    {
                        objValue = ((CheckBox)control).Checked;
                    }
                    else if (control is DropDownList)
                    {
                        objValue = ((DropDownList)control).SelectedValue;
                    }
                    else if (control is Label)
                    {
                        objValue = ((Label)control).Text;
                    }
                    else if (control is RadioButtonList)
                    {
                        objValue = ((RadioButtonList)control).SelectedValue;
                    }
                    //if (objValue != null && !objValue.ToString().Equals(String.Empty))
                    pi.SetValue(obj, getValueByType(objValue, pi.PropertyType), null);
                }
            }
            return obj;
        }

        /// <summary>
        /// Fill the obj's values into the container's control.
        /// </summary>
        /// <returns></returns>
        public static void ObjectIntoContent(Object obj, Control container, string[] prefixs)
        {
            PropertyInfo[] pis = obj.GetType().GetProperties();
            object objValue;
            Control control;
            foreach (PropertyInfo pi in pis)
            {
                control = null;
                if (prefixs != null)
                    for (int i = 0; i < prefixs.Length; i++)
                    {
                        control = container.FindControl(prefixs[i] + pi.Name);
                        if (control != null) break;
                    }
                else
                    control = container.FindControl(pi.Name);
                if (control != null)
                {
                    objValue = pi.GetValue(obj, null);
                    if (objValue != null)
                    {
                        if (control is TextBox)
                        {
                            ((TextBox)control).Text = objValue.ToString();
                        }
                        else if (control is CheckBox)
                        {
                            ((CheckBox)control).Checked = objValue.ToString().ToLower() == "true";
                        }
                        else if (control is DropDownList)
                        {
                            ((DropDownList)control).SelectedValue = objValue.ToString();
                        }
                        else if (control is Label)
                        {
                            ((Label)control).Text = objValue.ToString();
                        }
                        else if (control is RadioButtonList)
                        {
                            ((RadioButtonList)control).SelectedValue = objValue.ToString();
                        }
                    }
                }

            }
        }

        /// <summary>
        /// Clear the control's value in container.
        /// </summary>
        /// <returns></returns>
        public static void ClearContent(Control container)
        {
            foreach (Control control in container.Controls)
            {
                if (control is TextBox)
                {
                    ((TextBox)control).Text = "";
                }
                else if (control is CheckBox)
                {
                    ((CheckBox)control).Checked = false;
                }
                else if (control is DropDownList)
                {
                    ((DropDownList)control).SelectedIndex = -1;
                }
                else if (control is RadioButtonList)
                {
                    ((RadioButtonList)control).SelectedIndex = 0;
                }
            }
        }

        private static object getValueByType(object value, Type type)
        {
            if (type.Name.Equals("String"))
            {
                return value.ToString();
            }
            else
            {
                if (value.ToString().Trim().Length == 0) return null;
                if (type.Name.Equals("Int32"))
                {
                    return Convert.ToInt32(value);
                }
                else if (type.Name.Equals("Decimal"))
                {
                    return Convert.ToDecimal(value);
                }
                else if (type.Name.Equals("Boolean"))
                {
                    return Convert.ToBoolean(value);
                }
                else
                {
                    return null;
                }
            }
        }

        #region date time
        public static DateTime AddedEndDate(string date)
        {
            return DateTime.Parse(date).Add(new TimeSpan(23, 59, 59));
        }
        #endregion

        #region Encrypt 单向加密函数
        /// <summary>
        /// 单向加密函数
        /// </summary>
        /// <param name="PasswordString">原始的string,</param>
        /// <param name="PasswordFormat">加密方式</param>
        /// <returns>加密的string</returns>
        public static string Encrypt(string PasswordString, string PasswordFormat)
        {
            string EncryptPassword;

            if (PasswordFormat == "SHA1")
            {
                EncryptPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "SHA1");
            }
            else if (PasswordFormat == "MD5")
            {
                EncryptPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "MD5");
            }
            else
            {
                EncryptPassword = "";
            }

            return EncryptPassword;
        }
        #endregion

        #region DeTransform 可逆解密函数

        /// <summary>
        /// 可逆解密函数

        /// </summary>
        /// <param name="str">加密的string</param>
        /// <returns>原始的string</returns>
        public static string DeTransform(string str)
        {
            int i = 0;
            StringBuilder sb = new StringBuilder();

            foreach (char a in str)
            {
                switch (i % 6)
                {
                    case 0:
                        sb.Append((char)(a - 1));
                        break;
                    case 1:
                        sb.Append((char)(a - 5));
                        break;
                    case 2:
                        sb.Append((char)(a - 7));
                        break;
                    case 3:
                        sb.Append((char)(a - 2));
                        break;
                    case 4:
                        sb.Append((char)(a - 4));
                        break;
                    case 5:
                        sb.Append((char)(a - 9));
                        break;
                }
                i++;
            }

            return sb.ToString();
        }
        #endregion




        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
            {
                return HttpContext.Current.Request.Cookies[strName].Value.ToString();
            }
            return "";
        }
        public static bool delCookie(string strName)
        {
            try
            {
                HttpCookie Cookie = new HttpCookie(strName);
                Cookie.Expires = DateTime.Now.AddDays(-1);
                System.Web.HttpContext.Current.Response.Cookies.Add(Cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public static string DecrptString(string pszCode)
        {
            int nLen = pszCode.Length;
            string szDest = string.Empty;
            if (nLen < 0 || nLen % 2 != 0)
                return "";
            for (int i = 0; i < nLen; i = i + 2)
            {
                int iCode = Convert.ToInt32(pszCode.Substring(i, 2), 16);
                iCode -= 100;
                if (iCode < 32)
                    return "";
                szDest += (char)iCode;
            }
            return szDest;
        }

        public static string EncrptString(string pszCode)
        {
            string pszDest = "";
            int nLen = (int)pszCode.Length;
            if (nLen <= 0)
                return pszDest;
            char[] tmp = pszCode.ToCharArray();
            for (int i = 0; i < tmp.Length; i++)
            {
                int iCode = tmp[i];
                iCode += 100;
                pszDest += iCode.ToString("X2");
            }
            return pszDest;
        }


        /// <summary>
        /// 获取股票评级
        /// </summary>
        /// <returns></returns>
        public static string GetStockPJ(string stockcode)
        {
            string spanTPScore = "--";
            try
            {
                string key = "sdstockscoreex" + stockcode;
                var level = MemcachedTools.GetHQ(key);
                if (level != null)
                {
                    var strs = level.ToString().Split(',');
                    var strlevel = Common.GetLevelFlag(strs[10]).Split(',');
                    var levels = strlevel.Length > 1 ? strlevel[1] : "";
                    spanTPScore = (strlevel[0] + (strlevel.Length > 1 ? strlevel[1] : ""));
                }
            }
            catch (Exception)
            {
                //MyTrace.get().add("function GetStockPJ-Exception:" + ex.Message);
            }
            return spanTPScore;
        }
        public static string GetLevelFlag(string level)
        {
            switch (Convert.ToInt32(level))
            {
                case 1:
                    return "A,+";
                case 2:
                    return "A";
                case 3:
                    return "A,-";
                case 4:
                    return "B,+";
                case 5:
                    return "B";
                case 6:
                    return "B,-";
                case 7:
                    return "C,+";
                case 8:
                    return "C";
                case 9:
                    return "C,-";
                case 10:
                    return "D,+";
                case 11:
                    return "D";
                case 12:
                    return "D,-";
                default:
                    return "--,";
            }


        }
        public static string getWeekChStr(DayOfWeek a)
        {
            switch (a)
            {
                case DayOfWeek.Monday: return "一";
                case DayOfWeek.Tuesday: return "二";
                case DayOfWeek.Wednesday: return "三";
                case DayOfWeek.Thursday: return "四";
                case DayOfWeek.Friday: return "五";
                case DayOfWeek.Saturday: return "六";
                case DayOfWeek.Sunday: return "日";
                default: return "一";
            }
        }
        public static bool isPhoneNum(string phone)
        {
            if ("" != phone && Regex.IsMatch(phone, @"^\d{11}$"))
            {
                if (Regex.IsMatch(phone, @"^(13[4-9])|^(147)|^(150)|^(151)|^(152)|^(157)|^(158)|^(159)|^(178)|^(182)|^(183)|^(184)|^(187)|^(188)") || Regex.IsMatch(phone, @"^(130)|^(131)|^(132)|^(145)|^(155)|^(156)|^(176)|^(185)|^(186)") || Regex.IsMatch(phone, @"^(133)|^(153)|^(177)|^(180)|^(181)|^(189)") || Regex.IsMatch(phone, @"^(170)"))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public static void CreateExcel(DataSet ds, string FileName, HttpResponse resp)
        {
            int cl = ds.Tables[0].Columns.Count;
            string[] titles = new string[cl];
            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符
            for (int i = 0; i < cl; i++)
            {
                titles[i] = ds.Tables[0].Columns[i].Caption;
            }
            CreateExcel(ds, FileName, resp, titles);
        }
        public static void CreateExcel(DataSet ds, string FileName, HttpResponse resp, string[] titles)
        {
            //HttpResponse resp;
            //resp = Page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            resp.ContentType = "application/ms-excel";

            string colHeaders = "", ls_item = "";

            //定义表对象与行对象，同时用DataSet对其值进行初始化
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int i = 0;
            int cl = dt.Columns.Count;


            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符
            for (i = 0; i < titles.Length; i++)
            {
                if (i == (titles.Length - 1))//最后一列，加\n
                {
                    colHeaders += titles[i] + "\n";
                }
                else
                {
                    colHeaders += titles[i] + "\t";
                }
            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息

            //逐行处理数据  
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据    
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列，加\n
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }

                }
                resp.Write(ls_item);
                ls_item = "";

            }
            resp.End();
        }
        public static void CreateExcel<T>(List<T> dt, string FileName, HttpResponse resp, string[] titles)
        {
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            resp.ContentType = "application/ms-excel";

            string colHeaders = "", ls_item = "";

            //定义表对象与行对象，同时用DataSet对其值进行初始化  
            int i = 0;
            int cl = titles.Length;

            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符
            for (i = 0; i < titles.Length; i++)
            {
                if (i == (titles.Length - 1))//最后一列，加\n
                {
                    colHeaders += titles[i] + "\n";
                }
                else
                {
                    colHeaders += titles[i] + "\t";
                }
            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息 
            Type t = typeof(T);
            PropertyInfo[] propInfos = t.GetProperties();
            int j = 0;
            for (i = 0; i < dt.Count; i++)
            {
                j = 0;
                foreach (var pi in propInfos)
                {
                    object value = pi.GetValue(dt[i], null);
                    if (j == (cl - 1))//最后一列，加\n
                    {
                        ls_item += value.ToString() + "\n";
                    }
                    else
                    {
                        ls_item += value.ToString() + "\t";
                    }
                    resp.Write(ls_item);
                    ls_item = "";
                    j++;
                }
            }
            resp.End();
        }

        public static int StrToInt(string input)
        {
            return StrToInt(input, 0);
        }
        public static int StrToInt(string input, int defaultValue)
        {
            int result = 0;
            if (!int.TryParse(input, out result))
            {
                result = defaultValue;
            }
            return result;
        }

        public static DataSet GetDataSetByXmlData(string xmlData)
        {
            try
            {
                DataSet ds = new DataSet();
                using (StringReader xmlSR = new StringReader(xmlData))
                {
                    ds.ReadXml(xmlSR, XmlReadMode.InferTypedSchema); //忽视任何内联架构，从数据推断出强类型架构并加载数据。如果无法推断，则解释成字符串数据
                    if (ds.Tables.Count > 0)
                    {
                        return ds;
                    }
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
